package com.example.capsule.controller;

import com.example.capsule.dto.CapsuleResponse;
import com.example.capsule.entity.Capsule;
import com.example.capsule.service.CapsuleService;
import com.example.capsule.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 时光胶囊控制器
 */
@RestController
@RequestMapping("/api/capsules")
@Tag(name = "时光胶囊API", description = "时光胶囊的创建、查看和管理接口")
public class CapsuleController {

    private final CapsuleService capsuleService;
    private final UserService userService;

    public CapsuleController(CapsuleService capsuleService, UserService userService) {
        this.capsuleService = capsuleService;
        this.userService = userService;
    }

    /**
     * 创建时光胶囊 - 修改方法签名
     */
    @PostMapping(consumes = {"multipart/form-data"})
    @Operation(summary = "创建时光胶囊", description = "创建一个新的时光胶囊，可以包含文字和图片")
    public ResponseEntity<CapsuleResponse> createCapsule(
            @Parameter(description = "胶囊标题") @RequestParam String title,
            @Parameter(description = "胶囊内容") @RequestParam String content,
            @Parameter(description = "解锁时间") @RequestParam String unlockTime,
            @Parameter(description = "接收人联系方式") @RequestParam(required = false) String recipientContact,
            @Parameter(description = "是否公开") @RequestParam(required = false, defaultValue = "false") Boolean isPublic,
            @Parameter(description = "图片文件") @RequestParam(required = false) MultipartFile imageFile,
            @RequestHeader("Authorization") String authHeader) {

        try {
            String senderPhone = extractPhoneFromAuthHeader(authHeader);

            Capsule capsule = new Capsule();
            capsule.setTitle(title);
            capsule.setContent(content);
            capsule.setUnlockTime(java.time.LocalDateTime.parse(unlockTime));
            capsule.setSenderPhone(senderPhone);
            capsule.setIsPublic(isPublic); // 设置公开状态

            // 使用带邀请功能的方法
            Capsule savedCapsule = capsuleService.createCapsuleWithInvitation(capsule, imageFile, senderPhone, recipientContact);
            CapsuleResponse response = new CapsuleResponse(savedCapsule, capsuleService.getBaseUrl());

            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }

    /**
     * 添加新的API端点 - 修改胶囊公开状态
     */
    @PatchMapping("/{id}/visibility")
    @Operation(summary = "修改胶囊公开状态", description = "修改时光胶囊的公开/私有状态")
    public ResponseEntity<Void> updateCapsuleVisibility(
            @Parameter(description = "胶囊ID") @PathVariable Long id,
            @Parameter(description = "是否公开") @RequestParam Boolean isPublic,
            @RequestHeader("Authorization") String authHeader) {

        try {
            String userPhone = extractPhoneFromAuthHeader(authHeader);
            boolean success = capsuleService.updateCapsuleVisibility(id, userPhone, isPublic);

            if (success) {
                return ResponseEntity.ok().build();
            } else {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }

    /**
     * 获取所有已解锁的胶囊
     */
    @GetMapping
    @Operation(summary = "获取已解锁胶囊列表", description = "获取所有已经解锁的时光胶囊")
    public ResponseEntity<List<CapsuleResponse>> getAllUnlockedCapsules(
            @RequestHeader("Authorization") String authHeader) {

        String userPhone = extractPhoneFromAuthHeader(authHeader);
        List<Capsule> capsules = capsuleService.getAllUnlockedCapsules(userPhone);
        List<CapsuleResponse> responses = capsules.stream()
                .map(capsule -> new CapsuleResponse(capsule, capsuleService.getBaseUrl()))
                .collect(Collectors.toList());

        return ResponseEntity.ok(responses);
    }

    /**
     * 根据ID获取胶囊详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取胶囊详情", description = "根据ID获取时光胶囊的详细信息")
    public ResponseEntity<CapsuleResponse> getCapsuleById(
            @Parameter(description = "胶囊ID") @PathVariable Long id,
            @RequestHeader("Authorization") String authHeader) {

        String userPhone = extractPhoneFromAuthHeader(authHeader);
        Optional<Capsule> capsuleOptional = capsuleService.getCapsuleById(id, userPhone);

        if (capsuleOptional.isPresent()) {
            Capsule capsule = capsuleOptional.get();
            CapsuleResponse response = new CapsuleResponse(capsule, capsuleService.getBaseUrl());
            return ResponseEntity.ok(response);
        }

        return ResponseEntity.notFound().build();
    }

    /**
     * 删除胶囊
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除胶囊", description = "根据ID删除时光胶囊")
    public ResponseEntity<Void> deleteCapsule(
            @Parameter(description = "胶囊ID") @PathVariable Long id,
            @RequestHeader("Authorization") String authHeader) {

        try {
            String userPhone = extractPhoneFromAuthHeader(authHeader);
            boolean deleted = capsuleService.deleteCapsule(id, userPhone);

            if (deleted) {
                return ResponseEntity.noContent().build();
            } else {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取所有胶囊（包括未解锁的，仅用于管理）
     */
    @GetMapping("/admin/all")
    @Operation(summary = "获取所有胶囊", description = "获取所有时光胶囊（包括未解锁的）")
    public ResponseEntity<List<CapsuleResponse>> getAllCapsules() {
        List<Capsule> capsules = capsuleService.findAllCapsules();
        List<CapsuleResponse> responses = capsules.stream()
                .map(capsule -> new CapsuleResponse(capsule, capsuleService.getBaseUrl()))
                .collect(Collectors.toList());

        return ResponseEntity.ok(responses);
    }

    /**
     * 获取用户创建的胶囊
     */
    @GetMapping("/my-created")
    @Operation(summary = "获取用户创建的胶囊", description = "获取当前用户创建的所有时光胶囊")
    public ResponseEntity<List<CapsuleResponse>> getMyCreatedCapsules(
            @RequestHeader("Authorization") String authHeader) {

        String phone = extractPhoneFromAuthHeader(authHeader);
        List<Capsule> capsules = capsuleService.getUserCreatedCapsules(phone);
        List<CapsuleResponse> responses = capsules.stream()
                .map(capsule -> new CapsuleResponse(capsule, capsuleService.getBaseUrl()))
                .collect(Collectors.toList());

        return ResponseEntity.ok(responses);
    }

    /**
     * 获取用户收到的胶囊
     */
    @GetMapping("/my-received")
    @Operation(summary = "获取用户收到的胶囊", description = "获取当前用户收到的所有时光胶囊")
    public ResponseEntity<List<CapsuleResponse>> getMyReceivedCapsules(
            @RequestHeader("Authorization") String authHeader) {

        String phone = extractPhoneFromAuthHeader(authHeader);
        List<Capsule> capsules = capsuleService.getUserReceivedCapsules(phone);
        List<CapsuleResponse> responses = capsules.stream()
                .map(capsule -> new CapsuleResponse(capsule, capsuleService.getBaseUrl()))
                .collect(Collectors.toList());

        return ResponseEntity.ok(responses);
    }

    /**
     * 获取公开的胶囊
     */
    @GetMapping("/public")
    @Operation(summary = "获取公开胶囊", description = "获取所有公开的时光胶囊")
    public ResponseEntity<List<CapsuleResponse>> getPublicCapsules() {
        List<Capsule> capsules = capsuleService.getPublicCapsules();
        List<CapsuleResponse> responses = capsules.stream()
                .map(capsule -> new CapsuleResponse(capsule, capsuleService.getBaseUrl()))
                .collect(Collectors.toList());

        return ResponseEntity.ok(responses);
    }

    /**
     * 从认证头中提取手机号
     */
    private String extractPhoneFromAuthHeader(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            try {
                return userService.getPhoneFromToken(token);
            } catch (Exception e) {
                throw new RuntimeException("无效的认证信息");
            }
        }
        throw new RuntimeException("无效的认证信息");
    }
}